import React, { Component } from "react";
import { Card, Icon, Button, Table, Modal, message } from "antd";
import LinkButton from "../../../components/linkButton";
import "./index.less";
import {
  reqCategoryList,
  reqAddCategory,
  reqUpdateCategory,
} from "../../../api";
import AddFrom from "./addForm";
import UpdateForm from "./updateForm";

export default class Category extends Component {
  state = {
    loading: true,
    categorys: [],
    subCategorys: [],
    parentId: "0",
    parentName: "",
    showModalStatus: 0, //0不显示， 1添加， 2修改
  };

  getColumns = () => {
    this.columns = [
      { title: "分类的名称", dataIndex: "name", key: "_id" },
      {
        title: "操作",
        dataIndex: "",
        key: "_id2",
        width: 300,
        render: (category) => (
          <span>
            <LinkButton
              onClick={() => {
                this.showUpdate(category);
              }}
            >
              修改分类
            </LinkButton>
            {this.state.parentId === "0" ? (
              <LinkButton
                onClick={() => {
                  this.showSubCategorys(category);
                }}
              >
                查看子分类
              </LinkButton>
            ) : null}
          </span>
        ),
      },
    ];
  };

  getCategorys = async (parentId) => {
    this.setState({ loading: true });

    parentId = parentId || this.state.parentId;
    let data = await reqCategoryList(parentId);

    if (data.status === 0) {
      let categorys = data.data;
      if (parentId === "0") {
        this.setState({ categorys, loading: false });
      } else {
        this.setState({ subCategorys: categorys, loading: false });
      }
    } else {
      message.error("获取分类列表失败！");
    }
  };

  showCategorys = () => {
    this.setState({
      parentId: "0",
      parentName: "",
      subCategorys: [],
    });
  };

  showSubCategorys = (category) => {
    this.setState(
      {
        parentId: category._id,
        parentName: category.name,
      },
      () => {
        this.getCategorys();
      }
    );
  };

  changeShowModalStatus = (idx = 0) => {
    this.setState({
      showModalStatus: idx,
    });
  };

  showUpdate = (category) => {
    this.category = category;
    this.changeShowModalStatus(2);
  };

  updateCategory = () => {
    this.form.validateFields(async (err, values) => {
      if (!err) {
        this.changeShowModalStatus();

        let categoryId = this.category._id;
        let { categoryName } = values;
        let result = await reqUpdateCategory({ categoryId, categoryName });
        this.form.resetFields();

        if (result.status === 0) {
          this.getCategorys();
        } else {
          message.error("更新失败！");
        }
      } else {
        message.error("参数不符合要求！");
      }
    });
  };

  addCategory = () => {
    this.form.validateFields(async (err, values) => {
      if (!err) {
        this.changeShowModalStatus();

        let form = this.form;
        const { parentId, addCategoryName } = values;
        form.resetFields();
        let result = await reqAddCategory(parentId, addCategoryName);
        if (result.status === 0) {
          if (parentId === this.state.parentId) {
            this.getCategorys();
          } else if (parentId === "0") {
            this.getCategorys("0");
          }
        } else {
          message.error("更新失败！");
        }
      } else {
        message.error("参数不符合要求！");
      }
    });
  };

  constructor(props) {
    super(props);
    this.getColumns();
  }

  componentDidMount() {
    this.getCategorys();
  }

  render() {
    let { categorys, parentId, parentName, subCategorys, loading } = this.state;
    let category = this.category || {};

    let title =
      parentId === "0" ? (
        "一级分类列表"
      ) : (
        <span>
          <LinkButton onClick={this.showCategorys}>一级分类列表</LinkButton>
          <Icon type="arrow-right" />
          <span className="parentName">{parentName}</span>
        </span>
      );
    let extra = (
      <Button
        type="primary"
        onClick={() => {
          this.changeShowModalStatus(1);
        }}
      >
        <Icon type="plus" />
        添加
      </Button>
    );

    return (
      <Card title={title} extra={extra}>
        <Table
          className="table"
          bordered
          rowKey="_id"
          loading={loading}
          pagination={{
            pageSize: 5,
            showQuickJumper: true,
          }}
          columns={this.columns}
          dataSource={parentId === "0" ? categorys : subCategorys}
        />

        <Modal
          title="添加分类"
          visible={this.state.showModalStatus === 1}
          onOk={this.addCategory}
          onCancel={this.changeShowModalStatus}
        >
          <AddFrom
            categorys={categorys}
            parentId={parentId}
            getForm={(form) => (this.form = form)}
          />
        </Modal>

        <Modal
          title="更新分类"
          visible={this.state.showModalStatus === 2}
          onOk={this.updateCategory}
          onCancel={this.changeShowModalStatus}
        >
          <UpdateForm
            categoryName={category.name}
            getForm={(form) => (this.form = form)}
          />
        </Modal>
      </Card>
    );
  }
}
